﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Portfolio.IViews.Admin;
using Portfolio.Presenters.Admin;
using Portfolio.Entities;
using System.Data;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace Portfolio.UI.Admin.Controls
{
    public partial class AdminArticlesGridControl : System.Web.UI.UserControl, IAdminArticlesView
    {
        int _articleID;       
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (LoadArticlesSortBySearch != null)
                {
                    LoadArticlesSortBySearch(this, EventArgs.Empty);
                }

                if (LoadFieldsSearch != null)
                {                    
                    LoadFieldsSearch(this, EventArgs.Empty);       
                }                
            }

            if (Session["message_error"] != null && (Int32)Session["message_error"] == 1)
            {
                IsArticleUpdated = true;
                Session["message_error"] = null;
            }
            else
            {
                IsArticleUpdated = false;
            }

            IsArticleDel = false;
            IsArticleDelSel = false;
        }

        protected void gvArticles_RowCommand(object sender, GridViewCommandEventArgs e)
        {            
            ImageButton imgbtn;

            switch (e.CommandName.ToLower())
            {   
                case "imgbtnedit":
                    imgbtn = (ImageButton)e.CommandSource;
                    Response.Redirect("~/Admin/AdminEditArticle.aspx?articleId=" + Convert.ToInt32(imgbtn.CommandArgument));
                    
                break;

                case "imgbtndelete":
                    imgbtn = (ImageButton)e.CommandSource;
                    this._articleID = Convert.ToInt32(imgbtn.CommandArgument);
                    if (DeleteArticle != null)
                    {
                        DeleteArticle(this, EventArgs.Empty);                        
                    }
                    if (LoadArticlesSortBySearch != null)
                    {
                        LoadArticlesSortBySearch(this, EventArgs.Empty);
                    }
                break;    


            }           
        }

        protected void gvListArticles_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvListArticles.PageIndex = e.NewPageIndex;
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvListArticles.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void gvListArticles_Sorting(object sender, GridViewSortEventArgs e)
        {

            if (this.SortExpression == e.SortExpression)
            {
                if (this.SortDirection == "Ascending")
                {
                    e.SortDirection = System.Web.UI.WebControls.SortDirection.Descending;
                    this.SortDirection = "Descending";                                       
                }
                else
                {
                    e.SortDirection = System.Web.UI.WebControls.SortDirection.Ascending;
                    this.SortDirection = "Ascending";                    
                }
            }
            else
            {
                e.SortDirection = System.Web.UI.WebControls.SortDirection.Ascending;
                this.SortDirection = "Ascending";                
            }
            this.SortExpression = e.SortExpression;            
        }

        protected void gvListArticles_Sorted(object sender, EventArgs e)
        {
            //add current sorting state mark           
            
            foreach (DataControlField field in ((GridView)sender).Columns)
            {
                // strip off the old ascending/descending icon                      
                Regex r = new Regex(@"\s(\u25bc|\u25b2)");
                field.HeaderText = r.Replace(field.HeaderText, "");

                if (field.SortExpression != null && field.SortExpression == this.SortExpression)
                {
                    if (this.SortDirection == "Ascending")
                    {
                        field.HeaderText += " \u25b2";
                    }
                    else
                    {
                        field.HeaderText += " \u25bc";
                    }
                }
            }

            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void ddlActive_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void imgbtnDeleteChecked_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvListArticles.Rows)
            {
                CheckBox _cbTemp = row.FindControl("cbSelect") as CheckBox;
                if (_cbTemp.Checked == true)
                {
                    this._articleID = Convert.ToInt32(_cbTemp.Text);
                    if (DeleteArticle != null)
                    {
                        DeleteArticle(this, EventArgs.Empty);
                        IsArticleDel = false;
                        IsArticleDelSel = true;
                    }
                }
            }
            if (LoadArticlesSortBySearch != null)
            {
                LoadArticlesSortBySearch(this, EventArgs.Empty);
            }
        }

        protected void cbAllSelect_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox _cbTemp = (CheckBox)sender;
            if (_cbTemp.Checked == true)
            {
                foreach (GridViewRow row in gvListArticles.Rows)
                {
                    ((CheckBox)row.FindControl("cbSelect")).Checked = true;
                }
            }
            else
            {
                foreach (GridViewRow row in gvListArticles.Rows)
                {
                    ((CheckBox)row.FindControl("cbSelect")).Checked = false;
                }
            }
        }

        protected void imgbtnAddArticle_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminEditArticle.aspx");
        }

        protected void imgbtnCancel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("~/Admin/AdminMain.aspx");
        }

        protected void gvListArticles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                switch (DataBinder.Eval(e.Row.DataItem, "Status").ToString())
                {
                    case "0":
                        e.Row.Cells[5].Text = "Nieopublikowany";
                        break;
                    case "1":
                        e.Row.Cells[5].Text = "Opublikowany";
                        break;
                    case "2":
                        e.Row.Cells[5].Text = "Archiwalny";
                        break;
                }


            }
        }
       

        #region IAdminArticlesView members
       
        public event EventHandler<EventArgs> LoadArticlesSortBySearch;
        public event EventHandler<EventArgs> DeleteArticle;
        public event EventHandler<EventArgs> LoadFieldsSearch;

        public IList<ArtilcesGridV> ArticlesDataBind
        {
            set
            {                
                gvListArticles.DataSource = value;
                gvListArticles.DataBind();                
            }

        }

        public ArticleT Article
        {
          get 
          {
                ArticleT _article = new ArticleT();                
                _article.ArticleID = _articleID;
                return _article;
           }
            
        }

        public string SortDirection
        {
            get
            {
                if (ViewState["PreviousSortDirection"] == null)
                {
                    ViewState["PreviousSortDirection"] = "Ascending";
                }
                return (string)ViewState["PreviousSortDirection"];                           
            }

            set
            {
                ViewState["PreviousSortDirection"] = value;
            }
        }

        public string SortExpression
        {
            get
            {
                if (ViewState["PreviousSortExpression"] == null)
                {
                    ViewState["PreviousSortExpression"] = "Title";
                }
                return (string)ViewState["PreviousSortExpression"];
            }

            set
            {
                ViewState["PreviousSortExpression"] = value;
            }
        }

        public string SearchTitle
        {
            get 
            { 
                return txtSearchTitle.Text; 
            }
        }        

        public IViews.Common.DataSourceContainer CategoriesDataSource
        {
            set
            {                
                ddlCategories.DataSource = value.DataSource;
                ddlCategories.DataTextField = value.DataTextFieldName;
                ddlCategories.DataValueField = value.DataValueFieldName;
                ddlCategories.DataBind();                
            }
        }

        public IViews.Common.DataSourceContainer StatusDataSource
        {
            set
            {
                ddlStatus.DataSource = value.DataSource;
                ddlStatus.DataTextField = value.DataTextFieldName;
                ddlStatus.DataValueField = value.DataValueFieldName;
                ddlStatus.DataBind();             
            }
        }

        public IViews.Common.DataSourceContainer ActiveDataSource
        {
            set
            {
                ddlActive.DataSource = value.DataSource;
                ddlActive.DataTextField = value.DataTextFieldName;
                ddlActive.DataValueField = value.DataValueFieldName;
                ddlActive.DataBind();                
            }
        }
        public IViews.Common.DataSourceContainer PageSizeDataSource
        {
            set
            {
                ddlPageSize.DataSource = value.DataSource;
                ddlPageSize.DataTextField = value.DataTextFieldName;
                ddlPageSize.DataValueField = value.DataValueFieldName;                
                ddlPageSize.DataBind();
                ddlPageSize.Items.FindByValue(value.DataSelectedValue.ToString()).Selected = true;
            }
        }


        public int? SearchCategories
        {
            get 
            {
                if (string.IsNullOrEmpty(ddlCategories.SelectedValue))
                {
                    return null;
                }
                else
                {
                    return Int32.Parse(ddlCategories.SelectedValue);
                }
            }
        }

        public bool? SearchActive
        {
            get 
            {
                if (string.IsNullOrEmpty(ddlActive.SelectedValue))
                {
                    return null;
                }
                else
                {
                    return Convert.ToBoolean(Int32.Parse(ddlActive.SelectedValue));
                }        
                
            }
        }

        public byte? SearchStatus
        {
            get
            {
                if (string.IsNullOrEmpty(ddlStatus.SelectedValue))
                {
                    return null;
                }
                else
                {
                    return Byte.Parse(ddlStatus.SelectedValue);
                }
            }
        }

        public bool IsArticleUpdated
        {
            set
            {
                //if (value)
                //{
                //    divSuccess.Visible = value;
                //}
                divSuccess.Visible = value;
            }
        }

        public bool IsArticleDel
        {
            set
            {
                divSuccessDel.Visible = value;
            }
        }

        public bool IsArticleDelSel
        {
            set
            {
                divSuccessDelSel.Visible = value;
            }
        }

        public string PublishException
        {
            set
            {
                this.divError.Visible = true;
                this.valCustom.ErrorMessage = value;
                this.valCustom.IsValid = false;
            }
        }

        #endregion

       

       

        
        
    }
}